import { createWorker, Worker } from 'tesseract.js'

export class OcrService {
  private worker: Worker | null = null
  private loading: boolean = false

  // 初始化 Tesseract worker
  async init() {
    if (this.worker || this.loading) return
    this.loading = true
    this.worker = await createWorker()
    await this.worker.load()
    await this.worker.reinitialize('chi_sim+eng')
    this.loading = false
  }

  // 识别 base64 图片中的文字
  async recognize(base64: string): Promise<string> {
    await this.init()
    if (!this.worker) throw new Error('OCR worker 初始化失败')
    // 兼容 data:image/png;base64, 前缀
    const base64Data = base64.replace(/^data:image\/(png|jpeg);base64,/, '')
    const buffer = Buffer.from(base64Data, 'base64')
    const { data } = await this.worker.recognize(buffer)
    return data.text
  }

  // 释放资源
  async terminate() {
    if (this.worker) {
      await this.worker.terminate()
      this.worker = null
    }
  }
}

// 单例导出
export const ocrService = new OcrService()
